//
//  VideoTableViewController.m
//  QingSongYiKe
//
//  Created by lanou3g on 16/3/21.
//  Copyright © 2016年 wanshuai. All rights reserved.
//

#import "VideoTableViewController.h"
#import "MiddleView.h"
#import "MiddleCell.h"
#import "Models.h"
#import "UIImageView+WebCache.h"
#import "CDHttpHelper.h"
#import "MJRefresh.h"

#import <MediaPlayer/MediaPlayer.h>

@interface VideoTableViewController ()


//数据源数组
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSArray *titleArray;
//传值
@property (nonatomic,strong)NSString *str;
@property (nonatomic,strong)NSString *strNumber;

@property (nonatomic,strong)MiddleView *middleView;
@property (nonatomic,assign)NSInteger page;
//视频播放控制器
@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;

//@property(nonatomic,strong)UITableView *myTableView;
/** 加载动画*/
@property(nonatomic,strong) UIActivityIndicatorView *loadingAni;
@property(nonatomic,strong)NSNotificationCenter *notificationCenter;
@property(nonatomic,strong)UIImageView *backmovieplayer;

@property (nonatomic,strong)NSString *tempString;
@property (nonatomic,strong)NSString *coverString;

@end

@implementation VideoTableViewController

- (void)loadView
{
    self.middleView = [[MiddleView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.middleView;
}
- (NSArray *)titleArray
{
    if (!_titleArray)
    {
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
    NSString *a = @"http://c.m.163.com/nc/video/home/";
    NSString *b = @"-10.html";
    NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
    NSLog(@"%@",str);
    self.str = str;


    [self refresh];
    
}

#pragma mark -- 播放器
-(void)viewWillAppear:(BOOL)animated
{
    
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying||self.moviePlayer.playbackState == MPMoviePlaybackStatePaused)
    {
        [self.moviePlayer play];
    }
    else
    {
        [self show];
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    if ([self.moviePlayer isFullscreen])
    {
        [self.moviePlayer play];
    }
    else
    {
        [self.moviePlayer pause];
        self.moviePlayer=nil;
    }
}

- (BOOL)shouldAutorotate
{
    return YES;
}
/**
 *  支持横竖屏显示
 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

-(void)show
{
    
    self.middleView.myTableView.dataSource = self;
    self.middleView.myTableView.delegate = self;
    //self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.middleView.myTableView registerClass:[MiddleCell class] forCellReuseIdentifier:@"cell"];
    
    self.loadingAni=[[UIActivityIndicatorView alloc]init];
    self.loadingAni.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
}


//刷新
- (void)refresh
{
    // 设置回调, 一旦进入刷新状态, 就调用 target 的 action, 也就是调用self 的刷新方法
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 设置文字
    [header setTitle:@"下拉刷新" forState:(MJRefreshStateIdle)];
    [header setTitle:@"松开释放" forState:(MJRefreshStatePulling)];
    [header setTitle:@"正在刷新..." forState:(MJRefreshStateRefreshing)];
    
    // 进入刷新状态
    [header beginRefreshing];
    
    // 设置刷新控件
    self.middleView.myTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [footer setTitle:@"点击和上拉会加载更多" forState:(MJRefreshStateIdle)];
    [footer setTitle:@"正在加载更多" forState:(MJRefreshStatePulling)];
    [footer setTitle:@"没有更多了" forState:(MJRefreshStateNoMoreData)];
    
    // 字体
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    footer.stateLabel.textColor = [UIColor grayColor];
    self.middleView.myTableView.mj_footer = footer;
}
//下拉刷新
- (void)loadNewData
{
    [self.dataArray removeAllObjects];
    self.page = 0;
    
    [self initLayout];
}

//上拉加载
- (void)loadMoreData
{
    self.page += 10;
    [self initLayout];
}


- (void)panduan
{
    self.titleArray = [NSArray arrayWithObjects:@"新闻",@"美女",@"排行榜",@"社会",@"LOL",nil];
    NSInteger index = [self.titleArray indexOfObject:self.title];
    //if ([self.title isEqualToString: @"新闻"])
    if (index == 0)
    {
        NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
        NSString *a = @"http://c.m.163.com/nc/video/home/";
        NSString *b = @"-10.html";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
        NSLog(@"%@",str);
        self.str = str;

    }
    //else if ([self.title isEqualToString: @"体育"])
    else if (index == 1)
    {
        NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
        NSString *a = @"http://c.3g.163.com/nc/article/list/T1348649079062/";
        NSString *b = @"-20.html";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
        
        self.str = str;
        self.strNumber = @"T1348649079062";
    }
    else if ([self.title isEqualToString: @"财经"])
    {
        NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
        NSString *a = @"http://c.3g.163.com/nc/article/list/T1348648756099/";
        NSString *b = @"-20.html";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
        
        self.str = str;
        self.strNumber = @"T1348648756099";
    }
    else if ([self.title isEqualToString: @"科技"])
    {
        NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
        NSString *a = @"http://c.3g.163.com/nc/article/list/T1348649580692/";
        NSString *b = @"-20.html";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
        
        self.str = str;
        self.strNumber = @"T1348649580692";
    }
    else if ([self.title isEqualToString: @"游戏"])
    {
        NSString *w = [NSString stringWithFormat:@"%ld",(long)_page];
        NSString *a = @"http://c.3g.163.com/nc/article/list/T1348654151579/";
        NSString *b = @"-20.html";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",a,w,b];
        
        self.str = str;
        self.strNumber = @"T1348654151579";
    }
}
//解析数据

- (void)initLayout
{
    [self panduan];
    NSLog(@"%@",self.str);
    NSURL *url = [NSURL URLWithString: self.str];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    //子线程请求数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (NSString *string in dic.allKeys)
        {
            if ([string isEqualToString:@"videoList"])
            {
                for (NSDictionary *dict in [dic valueForKey:string])
                {
                    Models *model = [Models new];
                    [model setValuesForKeysWithDictionary:dict];
                    [self.dataArray addObject:model];
                    
                }
            }
        }
        //NSLog(@"%@",self.dataArray);
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.middleView.myTableView.mj_header endRefreshing];
    [self.middleView.myTableView.mj_footer endRefreshing];
    [self.middleView.myTableView reloadData];
    if (self.page >= 140)
    {
        [self.middleView.myTableView.mj_footer endRefreshingWithNoMoreData];
    }
}
//解析数据

- (void)initLayout2
{
    [self panduan];
    
    NSURL *url = [NSURL URLWithString: self.str];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    //子线程请求数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        for (NSDictionary *dic in dict[@"list"])
//        {
//            PhotoModel *photoModel = [PhotoModel new];
//            photoModel.title = dic[@"text"];
//            [self.photoDataArray addObject:photoModel];
//            
//            NSArray *arr = dic[@"gif"][@"images"];
//            if (arr.count > 1) {
//                [self.photoDataArray1 addObject:arr[0]];
        
//            }
//        }
        //NSLog(@"%@",self.dataArray);
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.middleView.myTableView.mj_header endRefreshing];
    [self.middleView.myTableView.mj_footer endRefreshing];
    [self.middleView.myTableView reloadData];
    if (self.page >= 140)
    {
        [self.middleView.myTableView.mj_footer endRefreshingWithNoMoreData];
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 280;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (cell == nil)
    {
        cell = [[MiddleCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"cell"];
    }
    // 选中cell不变色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    Models *tempModel = self.dataArray[indexPath.section];
    //初始图片
    [cell.btnimage sd_setImageWithURL:[NSURL URLWithString:tempModel.cover]];
    
    cell.btn.tag = indexPath.section;
    [cell.btn addTarget:self action:@selector(doput:) forControlEvents:UIControlEventTouchUpInside];
    cell.Labeltitle.text = tempModel.title;
    //播放次数
    NSString *str = [NSString stringWithFormat:@"播放次数:%@",tempModel.playCount];
    cell.playcountLabel.text = str;
    
    if (cell.btnimage == nil)
    {
        [cell.myImageView removeFromSuperview];
    }
    cell.playtimeLabel.text = tempModel.ptime;
    
    self.tempString = tempModel.mp4_url;
    return cell;
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying||self.moviePlayer.playbackState == MPMoviePlaybackStatePaused)
    {
        [self.backmovieplayer removeFromSuperview];
        [self.moviePlayer.view removeFromSuperview];
        self.moviePlayer = nil;
    }
}

-(void)doput:(UIButton *)btn
{
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying||self.moviePlayer.playbackState == MPMoviePlaybackStatePaused)
    {
        [self.backmovieplayer removeFromSuperview];
        [self.moviePlayer.view removeFromSuperview];
    }
    
    NSString *urlStr= [[self.dataArray objectAtIndex:btn.tag] mp4_url];
    NSString *UrlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    if (!_moviePlayer)
    {
        _moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
        _moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    }
    if ([self.moviePlayer isPreparedToPlay])
    {
        [_moviePlayer setContentURL:url];
        [self.backmovieplayer removeFromSuperview];
    }
    
    self.moviePlayer.view.frame = CGRectMake(10,(btn.tag)*280+20,self.view.frame.size.width-20, 210);
    self.loadingAni.frame = CGRectMake(self.moviePlayer.view.bounds.size.width/2-18.5,self.moviePlayer.view.bounds.size.height/2-18.5, 37, 37);
    [self.middleView.myTableView addSubview:self.moviePlayer.view];
    
    self.backmovieplayer = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width-20, 210)];
    self.backmovieplayer.image=[UIImage imageNamed:@"night_sidebar_cellhighlighted_bg@2x"];
    //[self.backmovieplayer sd_setImageWithURL:[NSURL URLWithString:self.coverString]];
    
    [self.moviePlayer.view addSubview:self.backmovieplayer];
    [self.backmovieplayer addSubview:self.loadingAni];
    [self addNotification];
    [self.loadingAni startAnimating];
    [self.middleView.myTableView reloadData];
    
}

-(void)addNotification{
    
    self.notificationCenter=[NSNotificationCenter defaultCenter];
    
    [self.notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    
    if ([self.moviePlayer respondsToSelector:@selector(loadState)])
    {
        [self.moviePlayer prepareToPlay];
    }
    else
    {
        [self.moviePlayer play];
    }
    [self.notificationCenter addObserver:self selector:@selector(mediaPlayerPlayFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
}
/**
 *  播放状态改变，注意播放完成时的状态是暂停
 *
 *  @param notification 通知对象
 */

-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification
{
    [self.loadingAni stopAnimating];
    [self.backmovieplayer removeFromSuperview];
    if ([self.moviePlayer loadState] != MPMovieLoadStateUnknown)
    {
        switch (self.moviePlayer.playbackState)
        {
            case MPMoviePlaybackStatePlaying:
                
                //  NSLog(@"正在播放...");
                break;
            case MPMoviePlaybackStatePaused:
                // NSLog(@"暂停播放.");
                break;
            case MPMoviePlaybackStateStopped:
                // NSLog(@"停止播放.");
                break;
            default:
                // NSLog(@"播放状态:%li",self.moviePlayer.playbackState);
                break;
        }
    }
}

/**
 *  播放完成
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlayFinished:(NSNotification *)notification
{
    //NSLog(@"播放完成.%li",self.moviePlayer.playbackState);
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
